package com.hspedu.homework.homework3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/3
 * @time 18:36
 */
public class TCPServerDownload {
    public static void main(String[] args) throws Exception {
        //客户端要求下载的文件名字
        String downloadFile = null;

        //真正传输的文件名
        String resFile = null;

        //1. 监听端口
        ServerSocket serverSocket = new ServerSocket(9999);
        //2. 等待客户端连接
        Socket accept = serverSocket.accept();
        //3. 读取要下载的文件名
        InputStream inputStream = accept.getInputStream();
        int readLength = 0;
        byte[] readBuffer = new byte[1024];
        while ((readLength = inputStream.read(readBuffer)) != -1){
            downloadFile = new String(readBuffer, 0, readLength);
        }

        String path = "D:\\BaiduNetdiskDownload\\韩顺平2021基础学Java\\资料\\分享资料";
        File file = new File(path);
        String[] list = file.list();
        for (String fileName : list) {
            if (fileName.equals(downloadFile)){
                resFile = path+"\\"+downloadFile;
                break;
            }

            resFile = path+"\\bg.png";
        }

        System.out.println(resFile);
        //创建一个输入流读取文件
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(resFile));
        //使用StreamUtils读取文件到一个字节数组
       //byte[] bytes = StreamUtils.streamToByteArray(bis);
        //得到Socket关联的输出流
        BufferedOutputStream bos = new BufferedOutputStream(accept.getOutputStream());
//        bos.write(bytes);
//        accept.shutdownOutput();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }
        bos.flush();
        accept.shutdownOutput();

        accept.close();
        serverSocket.close();

    }
}
